#include "interface.h"

/*************************SI24R1*************************/

void MySPI_W_CSN(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA,GPIOA_SI24R1_CSN,(BitAction)BitValue);
}

void MySPI_W_SCK(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA,GPIOA_SI24R1_SCK,(BitAction)BitValue);
}

void MySPI_W_MOSI(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA,GPIOA_SI24R1_MOSI,(BitAction)BitValue);
}

uint8_t MySPI_R_MISO(void)
{
	return GPIO_ReadInputDataBit(GPIOA, GPIOA_SI24R1_MISO);
}

uint8_t MySPI_R_IRQ(void)
{
	return GPIO_ReadInputDataBit(GPIOA, GPIOA_SI24R1_IRQ);
}

void MySPI_W_CE(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA,GPIOA_SI24R1_CE,(BitAction)BitValue);
}

/******************************EEPROM**********************************/
void PAGE_Write(uint8_t * address)
{
	uint8_t max_retries = 0;
	__disable_irq();
	FLASH_Unlock();
	FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP|FLASH_FLAG_PGERR |FLASH_FLAG_WRPERR);
	FLASH_ErasePage((uint32_t)0x08003800);
	while((FLASH_GetStatus() != FLASH_COMPLETE) && max_retries < 3)
	{
		FLASH_ErasePage((uint32_t)0x08003800);
		max_retries ++;
	}

	for(uint8_t i = 0; i < 5; i++)
	{
		FLASH_ProgramHalfWord((uint32_t)(0x08003800 + i*2),(uint16_t)(address[i]));
		while((FLASH_GetStatus() != FLASH_COMPLETE) && (max_retries < 3))
		{
			FLASH_ProgramHalfWord((uint32_t)(0x08003800 + i*2),(uint16_t)(address[i]));
			max_retries ++;
		}
		max_retries = 0;
	}
	FLASH_Lock();
	__enable_irq(); 
}

volatile uint16_t* head_address = 0;
void INITIALIZE_PAGE_Write(uint8_t* address)
{
	head_address = (volatile uint16_t*)0x08003800;
	if(*head_address == address[0])	return;
	uint8_t max_retries = 0;
	__disable_irq();
	FLASH_Unlock();
	FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP|FLASH_FLAG_PGERR |FLASH_FLAG_WRPERR);
	FLASH_ErasePage((uint32_t)0x08003800);
	while((FLASH_GetStatus() != FLASH_COMPLETE) && max_retries < 3)
	{
		FLASH_ErasePage((uint32_t)0x08003800);
		max_retries ++;
	}

	for(uint8_t i = 0; i < 5; i++)
	{
		FLASH_ProgramHalfWord((uint32_t)(0x08003800 + i*2),(uint16_t)(address[i]));
		while((FLASH_GetStatus() != FLASH_COMPLETE) && (max_retries < 3))
		{
			FLASH_ProgramHalfWord((uint32_t)(0x08003800 + i*2),(uint16_t)(address[i]));
			max_retries ++;
		}
		max_retries = 0;
	}
	FLASH_Lock();
	__enable_irq(); 
}

/*******************************CONTROL ONOFF POWER************************************/

void Control_ST_OnOff(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOA,GPIO_Pin_4,(BitAction)BitValue);
}

/***********************************ADDRESS KEY RESERT*******************************/
uint8_t SCAN_KEY_Function(void)
{
	return GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_9);
}
